package handlers

import (
	"net/http"
	"strconv"

	"toolsweb-admin/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func ListToolCategories(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	var categories []models.ToolCategory
	if err := db.Preload("Tools").Find(&categories).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
		return
	}
	c.JSON(http.StatusOK, categories)
}

func CreateToolCategory(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	var category models.ToolCategory
	if err := c.ShouldBindJSON(&category); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	if err := db.Create(&category).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建失败"})
		return
	}
	c.JSON(http.StatusCreated, category)
}

func UpdateToolCategory(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	id, _ := strconv.Atoi(c.Param("id"))

	var category models.ToolCategory
	if err := db.First(&category, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "分类不存在"})
		return
	}

	if err := c.ShouldBindJSON(&category); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	db.Save(&category)
	c.JSON(http.StatusOK, category)
}

func DeleteToolCategory(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	id, _ := strconv.Atoi(c.Param("id"))

	if err := db.Delete(&models.ToolCategory{}, id).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除失败"})
		return
	}
	c.JSON(http.StatusNoContent, nil)
}

func GetCategoryTools(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	id, _ := strconv.Atoi(c.Param("id"))

	var tools []models.ToolItem
	if err := db.Where("tool_category_id = ?", id).Find(&tools).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
		return
	}
	c.JSON(http.StatusOK, tools)
}
